package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import pojo.SysM;
import pojo.User;
import service.SysMService;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/Img")
public class ImgController {

    @Autowired
    private SysMService sysMService;

    @RequestMapping("/gotoedit")
    public String gotoedit(){
        return "/WEB-INF/view/Img/img.jsp";
    }

    @RequestMapping("/upFile")
    public String upFile(MultipartHttpServletRequest request, HttpSession session){
        MultipartFile file1 = request.getFile("file1");
        System.out.println("I accept the file-" + file1.getOriginalFilename());
        User user1 = (User)session.getAttribute("USER_SESSION");
        String username = user1.getUsername();

        String path = request.getServletContext().getRealPath("static/img/") + username + ".jpg";
        File file = new File(request.getServletContext().getRealPath("static/img/") + username + ".jpg");

        SysM sysM = sysMService.getOne(username);
        sysM.setImg(path);
        sysMService.update(sysM);

        //  如果文件夹img文件夹不存在，则创建
        if (!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        //  如果文件不存在，则创建一个空文件，等待下面的file1.transferTo(file)向里面塞
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            file1.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "/WEB-INF/view/administrators/admins.jsp";
    }
}
